package com.fosss.band.service.impl;

import com.fosss.band.constant.FollowType;
import com.fosss.band.entity.Band;
import com.fosss.band.entity.Follow;
import com.fosss.band.entity.Member;
import com.fosss.band.entity.dto.BandDto;
import com.fosss.band.entity.vo.BandVo;
import com.fosss.band.entity.vo.MemberVo;
import com.fosss.band.mapper.BandMapper;
import com.fosss.band.mapper.FollowMapper;
import com.fosss.band.mapper.MemberMapper;
import com.fosss.band.service.BandService;
import com.fosss.band.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.fosss.band.utils.ResultCodeEnum.BAND_NAME_NULL;
import static com.fosss.band.utils.ResultCodeEnum.MESSAGE_UN_ENOUGH;

/**
 * @author: fosss
 * Date: 2023/12/27
 * Time: 20:37
 * Description:
 */
@Service
public class BandServiceImpl implements BandService {

    @Resource
    private BandMapper bandMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private FollowMapper followMapper;

    /**
     * 分页查询乐队信息
     */
    @Override
    public Result getBandListPage(Integer userId, Integer page, Integer size, String name) {
        //开启分页
        PageHelper.startPage(page, size);
        //条件查询
        List<Band> list = bandMapper.selectByCondition(name);
        List<BandDto> collect = list.stream().map(band -> {
            BandDto bandDto = new BandDto();
            BeanUtils.copyProperties(band, bandDto);
            //查询该用户是否关注
            Follow follow = followMapper.select(userId, FollowType.FOLLOW_TYPE_BAND, band.getId());
            bandDto.setFollowed(follow != null);
            return bandDto;
        }).collect(Collectors.toList());
        PageInfo<Band> pageInfo = new PageInfo<>(list);

        return Result.ok().data("rows", collect).data("total", pageInfo.getTotal());
    }

    /**
     * 删除乐队
     */
    @Override
    public Result removeById(Integer id) {
        bandMapper.deleteById(id);
        return Result.ok();
    }

    /**
     * 新增乐队
     */
    @Override
    public Result add(BandVo bandVo) {
        if (bandVo.getName() == null)
            return Result.error().code(BAND_NAME_NULL.getCode()).message(BAND_NAME_NULL.getMessage());
        Band band = new Band();
        band.setName(bandVo.getName());
        band.setDescription(bandVo.getDescription());
        band.setCreateTime(new Date());
        bandMapper.insert(band);
        return Result.ok();
    }

    /**
     * 查询单个乐队
     */
    @Override
    public Result getBandById(Integer id) {
        Band band = bandMapper.selectById(id);
        //封装返回的数据（将队长id转为姓名）
        BandDto bandDto = new BandDto();
        bandDto.setId(id);
        bandDto.setName(band.getName());
        bandDto.setDescription(band.getDescription());
        //查询成员名字
        Member member = memberMapper.selectById(band.getLeaderId());
        //有可能没队长！！！！！！！
        if (member != null) {
            bandDto.setLeaderId(member.getId());
            bandDto.setLeader(member.getName());
        }
        return Result.ok().data("row", bandDto);
    }

    /**
     * 根据乐队id查询成员
     */
    @Override
    public Result getMembersByBandId(Integer bandId) {
        List<Member> list = memberMapper.selectByBandId(bandId);
        return Result.ok().data("rows", list);
    }

    /**
     * 更新乐队信息
     *
     * @param band
     */
    @Override
    public Result updateBand(Band band) {
        if (band == null || StringUtils.isEmpty(band.getName()) || StringUtils.isEmpty(band.getDescription())) {
            return Result.error().code(MESSAGE_UN_ENOUGH.getCode()).message(MESSAGE_UN_ENOUGH.getMessage());
        }
        bandMapper.update(band);
        return Result.ok();
    }

    /**
     * 删除成员，直接将成员的离开时间设置上，设置乐队id为负的原id
     */
    @Transactional
    @Override
    public Result deleteMember(Integer id) {
        Date leaveTime = new Date();
        Member member = memberMapper.selectById(id);
        memberMapper.update(id, leaveTime, -member.getBandId());
        //乐队人数-1
        Band band = bandMapper.selectById(member.getBandId());
        bandMapper.updateMemberCount(member.getBandId(), band.getMemberCount() - 1);
        return Result.ok();
    }

    /**
     * 查询成员信息
     */
    @Override
    public Result selectMember(Integer id) {
        Member member = memberMapper.selectById(id);
        return Result.ok().data("data", member);
    }

    /**
     * 编辑成员
     */
    @Override
    public Result updateMember(MemberVo memberVo) {
        //因为乐队id没传过来，所以先查一下成员原信息
        Member member = memberMapper.selectById(memberVo.getId());
        member.setName(memberVo.getName());
        member.setGender(memberVo.getGender());
        member.setAge(memberVo.getAge());
        member.setRole(memberVo.getRole());
        memberMapper.updateMember(member);
        return Result.ok();
    }

    /**
     * 添加成员
     */
    @Transactional
    @Override
    public Result addMember(MemberVo memberVo) {
        if (StringUtils.isEmpty(memberVo.getName()) || StringUtils.isEmpty(memberVo.getRole()) || memberVo.getAge() == null
                || memberVo.getGender() == null) {
            return Result.error().code(MESSAGE_UN_ENOUGH.getCode()).message(MESSAGE_UN_ENOUGH.getMessage());
        }
        Member member = new Member();
        member.setName(memberVo.getName());
        member.setGender(memberVo.getGender());
        member.setAge(memberVo.getAge());
        member.setBandId(memberVo.getBandId());
        member.setRole(memberVo.getRole());
        member.setJoinTime(new Date());
        memberMapper.insert(member);

        Band band = bandMapper.selectById(member.getBandId());
        bandMapper.updateMemberCount(member.getBandId(), band.getMemberCount() + 1);
        return Result.ok();
    }

    /**
     * 查询所有乐队
     */
    @Override
    public Result selectAll() {
        List<Band> list = bandMapper.selectByCondition("");
        return Result.ok().data("rows", list);
    }

    /**
     * 批量查询乐队信息
     */
    @Override
    public List<BandDto> getBandDtoByIds(List<Integer> ids) {
        List<Band> bandList = bandMapper.selectBands(ids);
        //封装所需数据
        List<BandDto> collect = bandList.stream().map(band -> {
            BandDto bandDto = new BandDto();
            BeanUtils.copyProperties(band, bandDto);
            //有队长的前提下，查询队长名
            if (band.getLeaderId() != null) {
                Member leader = memberMapper.selectById(band.getLeaderId());
                bandDto.setLeader(leader.getName());
            }

            return bandDto;
        }).collect(Collectors.toList());
        return collect;
    }


}












